package com.uduemc.jcms.backend.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.uduemc.jcms.backend.BackendModule;
import com.uduemc.jcms.backend.component.BackendLoginForm;
import com.uduemc.jcms.backend.service.IBJcmsRepertoryService;
import com.uduemc.jcms.common.utils.JsonResult;
import com.uduemc.jcms.component.RepertoryUtil;
import com.uduemc.jcms.generate.entity.JcmsRepertory;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Controller
@RequestMapping(BackendModule.BaseRequest + "/upload")
@Slf4j
public class BUploadController {

	@Autowired
	RepertoryUtil repertoryUtil;

	@Autowired
	IBJcmsRepertoryService bjcmsRepertoryServiceImpl;

	@Autowired
	BackendLoginForm backendLoginForm;

	@PostMapping(value = "/handle.html")
	@ResponseBody
	@Transactional
	public JsonResult index(@RequestParam(value = "file", required = false) MultipartFile file) {

		// 文件名使用上传时的名称
		String originalFilename = file.getOriginalFilename();
		// 获取文件的后缀
		String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());

		// 验证是否可以上传
		// 查看ext后缀是否允许上传
		if (!repertoryUtil.allowSuffix(ext)) {
			return JsonResult.messageError("未被允许的上传文件类型！");
		}
		// type类型的判断上传 https://blog.csdn.net/qq_30865917/article/details/88537977
		// 大小是否允许被上传
		String sizeErrMsg = repertoryUtil.size(file);
		if (StrUtil.isNotBlank(sizeErrMsg)) {
			return JsonResult.messageError(sizeErrMsg);
		}

		// 获取当前站点以及时间的不重复的一个值
		String unidname = bjcmsRepertoryServiceImpl.makeUnidname();

		LocalDateTime createAt = LocalDateTime.now();

		String path = repertoryUtil.getRepertoryPathByDate(createAt, unidname + "." + ext);

		String fullPath = repertoryUtil.getRepertoryFullPathByPath(path);

		// 生成不存在的目录
		File uploadFile = new File(fullPath);
		File parentFile = new File(uploadFile.getParent().toString());
		if (!parentFile.isDirectory()) {
			if (!parentFile.mkdirs()) {
				return JsonResult.assistance();
			}
		}

		// 生成缩放文件资源相对路径目录，不进行目录创建，预留后期功能需要
		String zoompath = repertoryUtil.getRepertoryPathByDate(createAt) + "/" + unidname;
		File zoomFile = new File(zoompath);
		zoompath = zoomFile.toString();

		// 判断是否是图片，如果是则获取图片的像素
		InputStream inputStream = null;
		BufferedImage image = null;
		try {
			inputStream = file.getInputStream();
			image = ImageIO.read(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String pixel = "";
		if (image != null) {
			pixel = image.getWidth() + "X" + image.getHeight();
		}

		// 写入数据
		JcmsRepertory jcmsRepertory = new JcmsRepertory();
		jcmsRepertory.setUserType(1);
		jcmsRepertory.setAimId(backendLoginForm.getUser().getId());
		jcmsRepertory.setLabelId(0);
		jcmsRepertory.setType(repertoryUtil.type(file));
		jcmsRepertory.setOriginalFilename(originalFilename);
		jcmsRepertory.setLink("");
		jcmsRepertory.setSuffix(ext);
		jcmsRepertory.setContentType(file.getContentType());
		jcmsRepertory.setUnidname(unidname);
		jcmsRepertory.setFilepath(path);
		jcmsRepertory.setZoompath(zoompath);
		jcmsRepertory.setSize(file.getSize());
		jcmsRepertory.setPixel(pixel);
		jcmsRepertory.setRefuse(0);

		boolean save = bjcmsRepertoryServiceImpl.save(jcmsRepertory);
		if (!save) {
			return JsonResult.assistance();
		}

		try {
			file.transferTo(new File(fullPath.toString()));
		} catch (IOException e) {
			e.printStackTrace();
			String message = "上传文件时 transferTo 操作 IOException 异常: " + e.getMessage();
			log.error(message);
			// 删除存在的文件
			throw new RuntimeException(message);
		}

		return JsonResult.ok(jcmsRepertory);
	}

}
